﻿using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

using Infrastructure.NetExtensions;

namespace TempEmployees.Web
{
    public abstract class BaseGridView : ABaseUserControl
    {
        private const string DATA_TABLE = "BaseGridView_data_table";
        protected DataTable GridViewDataTable
        {
            get
            {
                return ViewState.Get<DataTable>(DATA_TABLE);
            }
            set
            {
                ViewState.Set<DataTable>(DATA_TABLE, value);
            }
        }

        public EventHandler IndexChangedEvent
        {
            set { GetGridView().SelectedIndexChanged += new EventHandler(value); }
        }

        public BaseGridView()
        {
            LocalDateTime.SetIsraelFormat();
        }

        protected abstract GridView GetGridView();

        protected abstract ObjectDataSource GetDataSource();

        protected virtual void SetGridView()
        {
            GridView gridView = GetGridView();
            gridView.Visible = true;
            gridView.DataBind();
        }

        public virtual DataTable GetDGridViewDataTable()
        {
            return GridViewDataTable;
        }

        public void Clear()
        {
            foreach (GridViewRow row in GetGridView().Rows)
            {
                row.Cells.Clear();
            }
            GetGridView().Visible = false;
        }

        public void RegisterEventSelcetedIndexChanged(EventHandler method)
        {
            GetGridView().SelectedIndexChanged += new EventHandler(method);
        }

        public void RegisterEventDataBound(EventHandler method)
        {
            GetGridView().DataBound += new EventHandler(method);
        }

        protected virtual void SetBalanceColumns(params int[] toSetColumns)
        {
            foreach (int toSetColumn in toSetColumns)
            {
                SetBalanceColumns(toSetColumn);
            }
        }

        protected virtual void SetBalanceColumns(int toSetColumn)
        {
            foreach (GridViewRow row in GetGridView().Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    double amount_value = double.Parse(row.Cells[toSetColumn].Text);

                    if (amount_value < 0)
                    {
                        amount_value *= -1;
                        row.Cells[toSetColumn].Text = string.Format("({0})", amount_value);
                        row.Cells[toSetColumn].CssClass = "minusAmountColor";
                    }
                    else
                    {
                        row.Cells[toSetColumn].CssClass = "pluseAmountColor";
                    }
                }
            }
        }

        public void ExportToExcel()
        {
            GetGridView().ExportToExcel();
        }

        #region ObjectDataSource work around
        protected void ObjectDataSource_ObjectDisposing(object sender, ObjectDataSourceDisposingEventArgs e)
        {
            e.Cancel = true;
        }

        protected void ObjectDataSource_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            e.ObjectInstance = this;
        }
        #endregion
    }

    #region GridViewExtensions

    public static class GridViewExtensions
    {
        public static void ExportToExcel(this GridView gridView, int maxPageSize = 500)
        {
            gridView.AllowSorting = false;
            int pageSize = gridView.PageSize;
            gridView.PageSize = maxPageSize;
            gridView.DataBind();

            PrepareGridViewForExport(gridView);

            HttpResponse response = HttpContext.Current.Response;
            string attachment = "attachment; filename=ExportedData.xls";

            response.ClearContent();
            response.AddHeader("content-disposition", attachment);
            response.ContentType = "application/ms-excel";

            WebControl frm = new WebControl(HtmlTextWriterTag.Form);
            frm.Attributes["runat"] = "server";
            frm.Controls.Add(gridView);

            using (StringWriter sw = new StringWriter())
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                frm.RenderControl(htw);
                response.Write(sw.ToString());
                response.End();
            }

            gridView.AllowSorting = true;
            gridView.PageSize = pageSize;
            gridView.DataBind();
        }

        private static void PrepareGridViewForExport(Control control)
        {
            Literal l = new Literal();
            for (int i = 0; i < control.Controls.Count; i++)
            {
                if (control.Controls[i].GetType() == typeof(LinkButton))
                {
                    l.Text = (control.Controls[i] as LinkButton).Text;
                    control.Controls.Remove(control.Controls[i]);
                    control.Controls.AddAt(i, l);
                }
                else if (control.Controls[i].GetType() == typeof(DropDownList))
                {
                    l.Text = (control.Controls[i] as DropDownList).SelectedItem.Text;
                    control.Controls.Remove(control.Controls[i]);
                    control.Controls.AddAt(i, l);
                }
                else if (control.Controls[i].GetType() == typeof(CheckBox))
                {
                    l.Text = (control.Controls[i] as CheckBox).Checked ? "True" : "False";
                    control.Controls.Remove(control.Controls[i]);
                    control.Controls.AddAt(i, l);
                }
                else if (control.Controls[i].GetType().ToString() == "System.Web.UI.WebControls.DataControlLinkButton")
                {
                    l.Text = (control.Controls[i] as LinkButton).Text;
                    control.Controls.Remove(control.Controls[i]);
                    control.Controls.AddAt(i, l);
                }
                if (control.Controls[i].HasControls())
                {
                    PrepareGridViewForExport(control.Controls[i]);
                }
            }
        }

    }

    #endregion
}
